package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@RestController //@Controller @Compone当前类的对象存入IOC容器 @ResponseBody当前类下的所有方法 响应回去json字符串
@RequestMapping("/employee") // 映射到当前模块
public class EmployeeController{

    @Autowired
    private EmployeeService employeeService;


    //员工登录
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        //验证是否正确获取到数据
        log.info(employee.toString());
        //①. 将页面提交的密码password进行md5加密处理, 得到加密后的字符串
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //②. 根据页面提交的用户名username查询数据库中员工数据信息
        //要发出什么样的SQL语句  select * from employee where username= ?
        LambdaQueryWrapper<Employee> qw=new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee emp=employeeService.getOne(qw);
        //③. 如果没有查询到, 则返回登录失败结果
        if(null==emp){
            return R.error("无此用户");
        }
        //④. 密码比对，如果不一致, 则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码有误");
        }
        //⑤. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if(emp.getStatus()==0){
            return R.error("账户已禁用");
        }
        //⑥. 登录成功，将员工id存入Session, 并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    //员工登录
    @PostMapping("/logout")
    public R<String> logout(HttpSession session){
        //清理session中保存的用户的ID
        session.removeAttribute("employee");
        return R.success("退出成功");
    }


    //新增员工
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        //打印employee 确认获取到数据
        log.info("新增员工，员工信息{}",employee);
        //设置初始密码为123456，并对其进行加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //获取当前登录的员工的id
        Long empId=(Long)request.getSession().getAttribute("employee");
        //为employee对象设置4个参数 创建人id,更新人di,创建时间,更新时间
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        employeeService.save(employee);
        //调用service的保存功能
        /*try {
            employeeService.save(employee);
        } catch (Exception e) {
            e.printStackTrace();
        }
         如果采用这种方式，虽然可以解决，但是存在弊端，需要我们在保存其他业务数据时，也需要在Controller方法中加上try...catch进行处理，代码冗余，不通用。
        */
        //创建 新增员工成功提示消息 R

        return R.success("新增员工成功");
    }


    //员工信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        //构造分页构造器
        Page pageInfo=new Page(page,pageSize);

        //#查询第1页10条数据
        //SELECT *  FROM employee LIMIT 0 ,10 ORDER BY DESC update_time
        //#通过姓名模糊搜索包含张的所有员工的第1页10条数据
        //SELECT *  FROM employee WHERE NAME LIKE '%n%' LIMIT 0 ,10  ORDER BY DESC update_time
        //构造条件构造器
        LambdaQueryWrapper<Employee> lqw=new LambdaQueryWrapper<>();
        //添加过滤条件  如果name不为空,拼凑 WHERE NAME LIKE '%n%' 条件
        lqw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        lqw.orderByDesc(Employee::getUpdateTime);
        //执行查询  pageInfo:分页条件   lqw:模糊查询 排序
        employeeService.page(pageInfo,lqw);
        return R.success(pageInfo);
        //将R对象转换为JSON格式的字符串向浏览器进行响应
        //R  code:1   data: Page
        //pageInfo:  total:9 currentPage:1 pageSize:10 records:[9个员工信息]
    }

    //根据id修改员工信息
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        //是否获取到数据
        log.info(employee.toString());
        //从sssion中获取用户id 登录的用户的ID
        Long empId=(Long)request.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
        //此时employee对象上哪些属性有值？
        employeeService.updateById(employee);

        return R.success("员工信息修改成功");

    }

    //根据ID查询员工信息
    //http://localhost:8080/employee/2
    @GetMapping("/{id}")
    public R<Employee> getByID(@PathVariable Long id){
        log.info("根据ID查询员工信息:{}",id);
        Employee employee = employeeService.getById(id);
        if(employee!=null){
            return R.success(employee);
        }
        return R.error("没有查询到对应的员工信息");
    }
}
